import axios from "axios";

// 创建axios实例
const api = axios.create({
  baseURL: "http://localhost:3000",
});
// 请求拦截器，添加AccessToken
api.interceptors.request.use(
  (config) => {
    const accessToken = sessionStorage.getItem("accessToken");
    if (accessToken) {
      config.headers["Authorization"] = `${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理Token过期
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  async (error) => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const refreshToken = sessionStorage.getItem("refreshToken");
      // 使用RefreshToken请求新的AccessToken
      const { accessToken } = await api.post("/refresh", { refreshToken });
      if (accessToken) {
        const newAccessToken = accessToken;
        // 更新存储的AccessToken
        sessionStorage.setItem("accessToken", newAccessToken);
        // 重新发起原始请求
        return api(originalRequest);
      } else {
        // 如果RefreshToken也过期，则跳转到登录页面
        alert("登录已过期或您还未登录");

        window.location.href = "/login";
        return;
      }
    }
    return Promise.reject(error);
  }
);

//暴露axios请求
export default api;
